package com.lzx.iteam.provider;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.lzx.iteam.EventsFragment;
import com.lzx.iteam.bean.EventListData;
import com.lzx.iteam.bean.ScheduleData;
import com.lzx.iteam.util.PreferenceUtil;

import java.util.ArrayList;

/**
 * Created by Megan on 16/3/21.
 */
public class ScheduleDB {
    private static final String DB_NAME = "schedule.db";
    private SQLiteDatabase mDb;

    private static final String TYPE = "type";
    private static final String ID = "event_id";
    private static final String EVENT_TITLE = "event_title";
    private static final String NOTICE = "notice";
    private static final String ALERT_DATETIME = "alert_datetime";
    private static final String START_DATETIME = "start_datetime";
    private static final String END_DATETIME = "end_datetime";
    private static final String CREATE_TIME = "create_time";
    private static final String REMARK = "remark";
    private static final String BOSS_UID = "boss_uid";
    private static final String DONE = "done";
    private static final String HIDDEN = "hidden";
    private static final String DELEGATE_USER = "delegate_user";
    private static final String DELEGATE_USERNAME = "delegater_username";
    private static final String ADDRESS = "address";
    private static final String UPDATE_TIME = "update_time";

    private static final String MEMBER_COUNT = "member_count";
    private static final String USER_IMG = "user_img";
    private static final String HAS_READ_COUNT = "has_read_count";
    private static final String HAS_READ = "has_read";
    private static final String IS_QRCODE = "is_qrcode";
    private static final String QRCODE = "qrcode";
    private static final String USER_TYPE = "user_type";

    public ScheduleDB(Context context) {
        PreferenceUtil mPreferenceUtil = PreferenceUtil.getInstance(context);
        mDb = context.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);

    }

    /**
     * 创建一张表名为年-月-日的日常表
     *
     * @param date 日期 格式为yyyy_MM_dd
     */
    private void createScheduleTable(String date) {
        mDb.execSQL("CREATE table IF NOT EXISTS _" + date
                        + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
                        + ID + " TEXT, "
                        + TYPE + " TEXT, "
                        + USER_TYPE + " TEXT, "
                        + EVENT_TITLE + " TEXT, "
                        + NOTICE + " TEXT, "
                        + ALERT_DATETIME + " TEXT, "
                        + START_DATETIME + " TEXT, "
                        + END_DATETIME + " TEXT, "
                        + CREATE_TIME + " TEXT, "
                        + REMARK + " TEXT, "
                        + BOSS_UID + " TEXT, "
                        + DONE + " TEXT, "
                        + HIDDEN + " TEXT, "
                        + DELEGATE_USER + " TEXT, "
                        + DELEGATE_USERNAME + " TEXT, "
                        + ADDRESS + " TEXT, "
                        + UPDATE_TIME + " TEXT, "
                        + MEMBER_COUNT + " TEXT, "
                        + USER_IMG + " TEXT, "
                        + HAS_READ + " TEXT, "
                        + HAS_READ_COUNT + " TEXT, "
                        + IS_QRCODE + " TEXT, "
                        + QRCODE + " TEXT ); "

        );
    }

    /**
     * 添加一个日程
     */
    public void addSchedule(String type, String date, Object object) {
        createScheduleTable(date);
        if ("1".equals(type)) {
            ScheduleData scheduleData = (ScheduleData) object;
            mDb.execSQL(
                    "insert into _" + date + " (" + ID + "," + TYPE + "," + EVENT_TITLE + "," + NOTICE + "," + HAS_READ + "," + ALERT_DATETIME + "," + START_DATETIME + "," + END_DATETIME + "," + CREATE_TIME + "," + REMARK + "," + DONE + "," + HIDDEN + "," + BOSS_UID + "," + DELEGATE_USER + "," + DELEGATE_USERNAME + "," + ADDRESS + "," + UPDATE_TIME
                            + ") values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                    new Object[]{scheduleData.getId(), scheduleData.getType(), scheduleData.getTitle(), scheduleData.getNotice(), scheduleData.getHasRead(), scheduleData.getAlertTime(), scheduleData.getStartTime(), scheduleData.getEndTime(), scheduleData.getCreateTime(), scheduleData.getRemark(), scheduleData.getDone(),scheduleData.getHidden(), scheduleData.getBossUid(), scheduleData.getPublishedUId(), scheduleData.getPublishedUName(), scheduleData.getAddress(), scheduleData.getUpdateTime()});

        } else {
            EventListData eventListData = (EventListData) object;
            mDb.execSQL(
                    "insert into _" + date + " (" + ID + "," + TYPE + "," + EVENT_TITLE + "," + MEMBER_COUNT + "," + USER_IMG + "," + START_DATETIME + "," + END_DATETIME + "," + CREATE_TIME + "," + REMARK + "," + BOSS_UID + "," + DELEGATE_USER + "," + DELEGATE_USERNAME + "," + ADDRESS + "," + UPDATE_TIME + "," + HAS_READ_COUNT + "," + HAS_READ + "," + IS_QRCODE + "," + QRCODE + "," + USER_TYPE
                            + ") values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                    new Object[]{eventListData.getId(), eventListData.getEventType(), eventListData.getEventTitle(), eventListData.getMemberCount(), eventListData.getEventAvatar(), eventListData.getActivityTime(), eventListData.getEndTime(), eventListData.getCreateTime(), eventListData.getContent1(), eventListData.getMyUserId(), eventListData.getUserId(), eventListData.getUserName(), eventListData.getActivitySite(), eventListData.getUpdateTime(), eventListData.getHasReadCount(), eventListData.getHasRead(), eventListData.getIsQrcode(), eventListData.getQrcode(), eventListData.getUserType()});

        }
    }

    /**
     * 查询某天的日程
     *
     * @return
     */
    //public ArrayList<EventReplyNewData> findScheduleByDate(String date, int currentPage, int pageSize) {
    public ArrayList<Object> findScheduleByDate(String date, String uid) {
        createScheduleTable(date);
        ArrayList<Object> datas = new ArrayList<Object>();
      /*  int start = (currentPage - 1) * pageSize;
        int end = start + pageSize;*/
        /*String sql = "select * from _" + eventID + " order by _id  desc limit  "
                + start + " , " + end;*/
        String sql = "select * from _" + date + " where boss_uid = " + uid + " order by _id  asc ";
        Cursor cursor = null;
        try {
            cursor = mDb.rawQuery(sql, null);
            while (cursor.moveToNext()) {
                if ("1".equals(cursor.getString(cursor.getColumnIndex(TYPE)))) {
                    ScheduleData scheduleData = new ScheduleData();
                    scheduleData.setPublishedUName(cursor.getString(cursor.getColumnIndex(DELEGATE_USERNAME)));
                    scheduleData.setPublishedUId(cursor.getString(cursor.getColumnIndex(DELEGATE_USER)));
                    scheduleData.setUpdateTime(cursor.getString(cursor.getColumnIndex(UPDATE_TIME)));
                    scheduleData.setRemark(cursor.getString(cursor.getColumnIndex(REMARK)));
                    scheduleData.setType(cursor.getString(cursor.getColumnIndex(TYPE)));
                    scheduleData.setStartTime(cursor.getString(cursor.getColumnIndex(START_DATETIME)));
                    scheduleData.setEndTime(cursor.getString(cursor.getColumnIndex(END_DATETIME)));
                    scheduleData.setAlertTime(cursor.getString(cursor.getColumnIndex(ALERT_DATETIME)));
                    scheduleData.setUpdateTime(cursor.getString(cursor.getColumnIndex(UPDATE_TIME)));
                    scheduleData.setHasRead(cursor.getString(cursor.getColumnIndex(HAS_READ)));
                    scheduleData.setDone(cursor.getString(cursor.getColumnIndex(DONE)));
                    scheduleData.setHidden(cursor.getString(cursor.getColumnIndex(HIDDEN)));
                    scheduleData.setId(cursor.getString(cursor.getColumnIndex(ID)));
                    scheduleData.setTitle(cursor.getString(cursor.getColumnIndex(EVENT_TITLE)));
                    scheduleData.setAddress(cursor.getString(cursor.getColumnIndex(ADDRESS)));
                    scheduleData.setNotice(cursor.getString(cursor.getColumnIndex(NOTICE)));
                    datas.add(scheduleData);
                } else {
                    EventListData eventListData = new EventListData();
                    eventListData.setUserName(cursor.getString(cursor.getColumnIndex(DELEGATE_USERNAME)));
                    eventListData.setUserId(cursor.getString(cursor.getColumnIndex(DELEGATE_USER)));
                    eventListData.setUpdateTime(cursor.getString(cursor.getColumnIndex(UPDATE_TIME)));
                    eventListData.setContent1(cursor.getString(cursor.getColumnIndex(REMARK)));
                    eventListData.setEventType(cursor.getString(cursor.getColumnIndex(TYPE)));
                    eventListData.setActivityTime(cursor.getString(cursor.getColumnIndex(START_DATETIME)));
                    eventListData.setEndTime(cursor.getString(cursor.getColumnIndex(END_DATETIME)));
                    eventListData.setUpdateTime(cursor.getString(cursor.getColumnIndex(UPDATE_TIME)));
                    eventListData.setEventId(cursor.getString(cursor.getColumnIndex(ID)));
                    eventListData.setEventTitle(cursor.getString(cursor.getColumnIndex(EVENT_TITLE)));
                    eventListData.setActivitySite(cursor.getString(cursor.getColumnIndex(ADDRESS)));
                    eventListData.setMemberCount(cursor.getString(cursor.getColumnIndex(MEMBER_COUNT)));
                    eventListData.setEventAvatar(cursor.getString(cursor.getColumnIndex(USER_IMG)));
                    eventListData.setHasReadCount(cursor.getString(cursor.getColumnIndex(HAS_READ_COUNT)));
                    eventListData.setHasRead(cursor.getString(cursor.getColumnIndex(HAS_READ)));
                    eventListData.setIsQrcode(cursor.getString(cursor.getColumnIndex(IS_QRCODE)));
                    eventListData.setQrcode(cursor.getString(cursor.getColumnIndex(QRCODE)));
                    eventListData.setUserType(cursor.getString(cursor.getColumnIndex(USER_TYPE)));
                    datas.add(eventListData);
                }

            }
        } catch (Exception e) {
            Log.d("schedule", "Exception" + e.toString());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return datas;
    }

    public ScheduleData findScheduleById(String date,String uid,String id){

        createScheduleTable(date);
        String sql = "select * from _" + date + " where boss_uid = " + uid + " and event_id = '" + id + "'";
        Cursor cursor = null;
        ScheduleData scheduleData = new ScheduleData();
        try {
            cursor = mDb.rawQuery(sql, null);
            if (cursor.moveToNext()){
                scheduleData.setPublishedUName(cursor.getString(cursor.getColumnIndex(DELEGATE_USERNAME)));
                scheduleData.setPublishedUId(cursor.getString(cursor.getColumnIndex(DELEGATE_USER)));
                scheduleData.setBossUid(uid);
                scheduleData.setUpdateTime(cursor.getString(cursor.getColumnIndex(UPDATE_TIME)));
                scheduleData.setRemark(cursor.getString(cursor.getColumnIndex(REMARK)));
                scheduleData.setType(cursor.getString(cursor.getColumnIndex(TYPE)));
                scheduleData.setStartTime(cursor.getString(cursor.getColumnIndex(START_DATETIME)));
                scheduleData.setEndTime(cursor.getString(cursor.getColumnIndex(END_DATETIME)));
                scheduleData.setAlertTime(cursor.getString(cursor.getColumnIndex(ALERT_DATETIME)));
                scheduleData.setUpdateTime(cursor.getString(cursor.getColumnIndex(UPDATE_TIME)));
                scheduleData.setHasRead(cursor.getString(cursor.getColumnIndex(HAS_READ)));
                scheduleData.setDone(cursor.getString(cursor.getColumnIndex(DONE)));
                scheduleData.setHidden(cursor.getString(cursor.getColumnIndex(HIDDEN)));
                scheduleData.setId(cursor.getString(cursor.getColumnIndex(ID)));
                scheduleData.setTitle(cursor.getString(cursor.getColumnIndex(EVENT_TITLE)));
                scheduleData.setAddress(cursor.getString(cursor.getColumnIndex(ADDRESS)));
                scheduleData.setNotice(cursor.getString(cursor.getColumnIndex(NOTICE)));
            }
        }catch (Exception e){
            Log.d("schedule", "Exception" + e.toString());
        }finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return scheduleData;
    }



    /**
     * 删除某张表下某条消息
     *
     * @param date
     * @param eventId
     * @return
     */
    public int deleteOneSchedule(String date, String eventId) {
        createScheduleTable(date);
        return mDb.delete("_" + date, ID + " = ? ", new String[]{eventId});
    }

    /**
     * 删除某张表下所有消息
     *
     * @param date
     * @return
     */
    public int deleteScheduleByDate(String date, String uid) {
        createScheduleTable(date);
        return mDb.delete("_" + date, BOSS_UID + " = ? ", new String[]{uid});
    }

    /**
     * 修改
     *
     * @param date
     */
    public void updateSchedule(String date, String type, Object object) {
        createScheduleTable(date);
        if ("1".equals(type)) {
            ScheduleData scheduleData = (ScheduleData) object;
            mDb.execSQL("update _" + date + " set " + EVENT_TITLE + " = " + scheduleData.getTitle() + " , " + ADDRESS + " = " + scheduleData.getAddress() + " , " + START_DATETIME + " = " + scheduleData.getStartTime() + " , " + END_DATETIME + " = " + scheduleData.getEndTime() + " , " + ALERT_DATETIME + " = " + scheduleData.getAlertTime() + " , " + NOTICE + " = " + scheduleData.getNotice() + " , " + REMARK + " = " + scheduleData.getRemark() + " where " + ID + " = " + scheduleData.getId()
                    , new Object[]{});
        }

    }

    /**
     * 修改
     *
     * @param date
     */
    public void updateScheduleDone(String date, String done, String eventId, String uid) {
        createScheduleTable(date);

        // 写法 1
        mDb.execSQL("update _" + date + " set done = " + done + " , has_read = 1" + " where boss_uid = "+  uid + " and event_id = '" + eventId + "'", new Object[]{});

        // 写法 2
        /*ContentValues values = new ContentValues();
        values.put(DONE,done);
        String[] whereArgs = new String[]{eventId,uid};
        mDb.update("_" + date,values," event_id = ? and boss_uid = ?",whereArgs);*/

    }

}
